package com.anpxd.erpad.ui

import android.animation.Animator
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.support.annotation.MainThread
import android.support.v4.content.ContextCompat
import android.support.v4.widget.SwipeRefreshLayout
import android.support.v7.widget.DividerItemDecoration
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.View
import android.view.ViewGroup
import com.anpxd.baselibrary.utils.AppManager
import com.anpxd.erpad.App
import com.anpxd.erpad.R
import com.anpxd.erpad.adapter.CarItemAdapter
import com.anpxd.erpad.bean.BusTag
import com.anpxd.erpad.bean.Search
import com.anpxd.erpad.net.ApiFactory
import com.anpxd.erpad.net.ErpApi
import com.anpxd.erpad.utils.BackHomeTimer
import com.anpxd.ewalker.utils.GsonUtil
import com.chad.library.adapter.base.BaseQuickAdapter
import com.gg.baseproject.Composers
import com.lsxiao.apollo.core.Apollo
import com.lsxiao.apollo.core.annotations.Receive
import com.socks.library.KLog
import com.tencent.bugly.crashreport.CrashReport
import io.reactivex.Observable
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.internal.subscriptions.SubscriptionHelper.cancel
import io.reactivex.internal.util.HalfSerializer.onComplete
import io.reactivex.internal.util.HalfSerializer.onNext
import io.reactivex.plugins.RxJavaPlugins.onSubscribe
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.empty_view.*
import kotlinx.android.synthetic.main.fragment_car_list.*
import java.util.concurrent.TimeUnit
import kotlin.concurrent.thread


/**
 * Creator : GG
 * Date    : 2018/1/19
 * Mail    : gg.jin.yu@gmai.com
 * Explain :
 */
class CarListFragment : BaseFragment(), BaseQuickAdapter.RequestLoadMoreListener, SwipeRefreshLayout.OnRefreshListener {

    companion object {
        fun newInstance(): CarListFragment = CarListFragment()
    }

    private var mSearch: Search = Search()

    private lateinit var mNoDataView: View

    private var mAutoScroll: Boolean = true//记录是不是自动滚动模式

//    private var mNoMoreData: Boolean = false//记录在自动滚动模式在  是否没有更多数据了(pageIndex)

    private val mPageSize = 15
    private val adapter: CarItemAdapter by lazy { CarItemAdapter() }

    private var mCurrentCounter = 0

    private var mPageIndex = 1

    private var mCurrentPosition = 0

    private var mDisposable: Disposable? = null

    private lateinit var manager: LinearLayoutManager

    private var loadDataFailed: Boolean = false

    override fun getLayoutResId(): Int = R.layout.fragment_car_list

    override fun onStart() {
        super.onStart()
        Apollo.emit(BusTag.carListFragmentStart)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        swipeRefresh.setColorSchemeResources(R.color.main_orange)

        swipeRefresh.setOnRefreshListener(this)
        manager = LinearLayoutManager(context)
        recyclerView.layoutManager = manager
        recyclerView.addItemDecoration(DividerItemDecoration(context, DividerItemDecoration.VERTICAL).apply {
            setDrawable(ContextCompat.getDrawable(this@CarListFragment.context!!, R.drawable.divider_grey_large_h)!!)
        })

        val listenner = object : RecyclerView.OnScrollListener() {

            override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                BackHomeTimer.getInstance().resetTime()//重置时间
            }
        }

        recyclerView.addOnScrollListener(listenner)

        mNoDataView = layoutInflater.inflate(R.layout.empty_view, recyclerView as ViewGroup, false)

        mNoDataView.setOnClickListener {
            mSearch = Search()
            onRefresh()
        }

        adapter.setOnLoadMoreListener(this, recyclerView)
        recyclerView.adapter = adapter
        mCurrentCounter = adapter.data.size
        adapter.onItemClickListener = BaseQuickAdapter.OnItemClickListener { _, _, position ->

            BackHomeTimer.getInstance().resetTime()//重置时间

            val state = adapter.data[position].isShow
            adapter.data[position].isShow = !state
            adapter.notifyItemChanged(position)
            if (mCurrentPosition != position) {
                adapter.data[mCurrentPosition].isShow = false
                adapter.notifyItemChanged(mCurrentPosition)
                mCurrentPosition = position
            }
        }

        KLog.w("user", App.instance.getUser())
        onRefresh()
    }

//    private fun setTimer() {
//        if (mDisposable != null && mDisposable?.isDisposed == true) {
//            mDisposable?.dispose()
//            mDisposable = null
//        }
//        Observable.interval(60 * 3, TimeUnit.SECONDS)
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(object : Observer<Long> {
//                    override fun onComplete() {
//                    }
//
//                    override fun onSubscribe(d: Disposable) {
//                        mDisposable = d
//                    }
//
//                    override fun onNext(t: Long) {
//                        KLog.w("time", t)
//                        mSearch = Search()
//                        onRefresh()
//                    }
//
//                    override fun onError(e: Throwable) {
//                    }
//
//                })
//    }

    override fun useBus(): Boolean = true


    @Receive(BusTag.search)
    fun setSearch(search: Search) {
        mSearch = search
        KLog.w("search", GsonUtil.toJson(search))
        onRefresh()
    }

    @Receive(BusTag.start)
    fun start() {

        startActivity(Intent(context, SortActivity::class.java).putExtra(SortActivity.KEY_DATA, GsonUtil.toJson(mSearch)))
    }

    override fun onLoadMoreRequested() {
        swipeRefresh.isEnabled = false
        if (adapter.data.size < mPageSize) {//数据少于15个 可以加载更多
            adapter.loadMoreEnd(true)
            swipeRefresh.isEnabled = true
        } else {
            mPageIndex += 1
            ApiFactory.getErpApi()
                    .carList(pageIndex = mPageIndex,
                            brandId = if (mSearch.brandId == 0) null else mSearch.brandId,
                            seriesId = if (mSearch.seriesId == 0) null else mSearch.seriesId,
                            fromCarAge = mSearch.fromCarAge,
                            toCarAge = mSearch.toCarAge,
                            fromMileage = mSearch.fromMileage,
                            toMileage = mSearch.toMileage,
                            fromRetailPrice = mSearch.fromRetailPrice,
                            toRetailPrice = mSearch.toRetailPrice
                    )
                    .compose(Composers.handleError())
                    .subscribe({

                        if (it.isEmpty()) {
                            adapter.loadMoreEnd()
                            CrashReport.postCatchedException(Throwable("response is null\n" + GsonUtil.toJson(mSearch)))
                        }
                        else {
                            adapter.addData(it)
                            mCurrentCounter = adapter.data.size
                            adapter.loadMoreComplete()
                        }
                        swipeRefresh.isEnabled = true
                    }, {
                        adapter.loadMoreFail()
                    })

        }
    }

    @Receive(BusTag.refresh)
    override fun onRefresh() {
        mPageIndex = 1
        mCurrentPosition = 0
        adapter.setEnableLoadMore(false)
        if (swipeRefresh != null)
            swipeRefresh.isRefreshing = true
        ApiFactory.getErpApi()
                .carList(pageIndex = mPageIndex,
                        brandId = if (mSearch.brandId == 0) null else mSearch.brandId,
                        seriesId = if (mSearch.seriesId == 0) null else mSearch.seriesId,
                        fromCarAge = mSearch.fromCarAge,
                        toCarAge = mSearch.toCarAge,
                        fromMileage = mSearch.fromMileage,
                        toMileage = mSearch.toMileage,
                        fromRetailPrice = mSearch.fromRetailPrice,
                        toRetailPrice = mSearch.toRetailPrice
                )
                .compose(Composers.handleError())
                .subscribe({
                    if (it.isEmpty()) {
                        adapter.emptyView = mNoDataView
                        CrashReport.postCatchedException(Throwable("response is null\n" + GsonUtil.toJson(mSearch)))
                    }
                    adapter.setNewData(it)
                    mCurrentCounter = mPageSize
                    swipeRefresh.isRefreshing = false
                    adapter.setEnableLoadMore(true)
                    manager.scrollToPositionWithOffset(0, 0)

                    //如果标记记录上一次请求失败, 则通知main重新加载二维码, 并修改标记
                    if (!loadDataFailed) Apollo.emit(BusTag.reloadData)
                    loadDataFailed = true

                }, {
                    adapter.loadMoreFail()
                    swipeRefresh.isRefreshing = false
                    //记录一下请求失败, 然后递归调用一下
                    loadDataFailed = false
                    onRefresh()
                })
    }

    @Receive(BusTag.gotoHome)
    fun gotoHome() {

        if (AppManager.getInstance().currentActivity()::class.java == MainActivity::class.java) {

            if (!mSearch.isEmpty()) {//如果有筛选条件, 重置筛选条件并刷新 然后自动滚屏
                mSearch = Search()
                onRefresh()
                return
            }

            //自动滚屏
            mAutoScroll = true
            autoScrollScreen()
            return
        }
        mSearch = Search()
        onRefresh()
        AppManager.getInstance().finishActivity(SortActivity::class.java)
    }

    @Receive(BusTag.didResetTime)
    fun didResetTime() {
        mAutoScroll = false
    }

    private fun autoScrollScreen() {

        val lastPosition = manager.findLastVisibleItemPosition()

        if (lastPosition == adapter.data.count()) {
            onRefresh()
            return
        } else {

            manager.scrollToPositionWithOffset(lastPosition, 0)
        }

        if (lastPosition == adapter.data.count() - 1 - 4) {
            onLoadMoreRequested()
        }
    }

}